package com.endava.exceptions.handling;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

/**
 * Example of handling exceptions: ArrayIndexOutOfBoundsException and
 * IOException. These exceptions are in different hierarchies so the order of
 * the catch blocks does not matter.
 * 
 * IndexOutOfBoundsException is the superclass of ArrayIndexOutOfBoundsException
 * and StringIndexOutOfBoundsException.
 * 
 * @author Andreea
 * 
 */
public class Example {
	// list of elements to be added to the file
	private static List<String> exceptions = Arrays.asList("Exception",
			"Error", "RuntimeException", "Throwable");

	public static void writeList() {
		PrintWriter out = null;

		try {
			System.out.println("Entering try statement");
			
			// an IOException may be thrown at this line:
			out = new PrintWriter(new FileWriter("output.txt"));
			System.out.println("File created.");
			
			// an ArrayIndexOutOfBoundsException may be thrown at this line:
			for (int i = 0; i < exceptions.size(); i++)
				out.println("Value at: " + i + " = " + exceptions.get(i));
			System.out.println("Information added to the file.");
			
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("Caught ArrayIndexOutOfBoundsException: "
					+ e.getMessage());									//print the message of the exception
		} catch (StringIndexOutOfBoundsException e) {						
			System.out.println("Caught StringIndexOutOfBoundsException: "
					+ e.getMessage());
		} catch (IndexOutOfBoundsException e) {
			System.out.println("Caught IndexOutOfBoundsException: "
					+ e.getMessage());
		} catch (IOException e) {
			System.out.println("Caught IOException: " + e.toString());	//print the type and the message of the exception

		} finally {
			//cleaning up
			if (out != null) {
				System.out.println("Closing PrintWriter");
				out.close();
			} else {
				System.out.println("PrintWriter not open");
			}
		}
	}

	public static void main(String[] args) {
		writeList();
	}
}
